package com.service.purchase;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.ContractDao;
import com.dao.purchase.OrderDao;
import com.dao.purchase.SupplyDealMapper;
import com.enums.ContractTypeEnum;
import com.model.purchase.ContractModel;
import com.model.purchase.OrderModel;
import com.model.purchase.PurchaseSupplyDeal;
import com.model.sys.DictGlobal;
import com.model.sys.SysDict;
import com.model.sys.SysUser;
import com.service.external.oa.CreateContractService;
import com.service.external.oa.GetWFStatusService;
import com.service.external.sap.SapPurchaseService;
import com.service.external.zkh.ZKHService;
import com.service.sys.SysDictService;

@Service
public class ContractService {
	static final Logger logger = LoggerFactory.getLogger(ContractService.class);

	@Autowired
	ContractDao contractDao;
	@Autowired
	OrderDao orderDao;
	@Autowired
	SapPurchaseService sapPurchaseService;
	@Autowired
	CreateContractService createContractService;
	@Autowired
	GetWFStatusService getWFStatusService;
	@Autowired
	SysDictService sysDictService;
	@Autowired
	ZKHService zkhService;
	@Autowired
	SupplyDealMapper supplyDealMapper;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<ContractModel> list = contractDao.selectList(queryMap);
		int count = contractDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String ctrId) {
		HttpResult httpResult = new HttpResult();
		ContractModel contractModel = contractDao.load(ctrId);
		httpResult.setData(contractModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(ContractModel contractModel) {
		if (contractModel == null) {
			return HttpResult.error("参数不能为空!");
		}
		OrderModel orderModel = orderDao.load(contractModel.getOrdId());
		if (orderModel == null) {
			return HttpResult.error("订单不存在！");
		}

		PurchaseSupplyDeal supplyDeal = supplyDealMapper.load(orderModel.getResId(), orderModel.getInfId());
		SysUser sysUser = SpringMvcUtils.getSysUser();

//		HashMap<String, Object> dicHashMap = new HashMap<String, Object>();
//		dicHashMap.put("dicName", DictGlobal.oaPurchaseCheckParentNameString);
//		dicHashMap.put("query", DictGlobal.oaPurchaseCheckNameString);
//		List<SysDict> dicts = sysDictService.queryItemByTypeName(dicHashMap);
//		if (dicts != null && dicts.size() > 0) {
//			String valueString = dicts.get(0).getDicValue();
//			BigDecimal bigDecimal = new BigDecimal(valueString);
//			if (bigDecimal.compareTo(orderModel.getOrdFreight()) <= 0) {
		if (orderModel.getOrdContractType() != null && orderModel.getOrdContractType().equals(Global.YES + "")) {
			if (getWFStatusService.getWFStatus(orderModel.getOaFlowId() + "", sysUser.getWxid())
					.getCode() != HttpStatus.SUCCESS_CODE) {
				return HttpResult.error("oa流程(" + orderModel.getOaFlowId() + ")未审批结束！");
			}
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;
		contractModel.setOrdContractId(orderModel.getOrdContractId());
		contractModel.setOrdContractName(orderModel.getOrdContractName());
		contractModel.setDeptName(orderModel.getInfName());
		if (!StringUtils.isNotNull(contractModel.getCtrId())) {
			contractModel.setCtrId(UUID.randomUUID().toString());
			result = contractDao.insert(contractModel);
		} else {
			result = contractDao.update(contractModel);
		}
		if (orderModel.getStatus().equals(Global.NUMERICAL_TWO + "")) {
			httpResult.setData(contractModel);
			httpResult.setMsg(contractModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			return httpResult;
		}
		if (contractModel.getStatus().equals(Global.YES + "")) {
			orderModel.setStatus(Global.NUMERICAL_TWO + "");// 将订单状态置为2
			orderDao.update(orderModel);
			if (orderModel.getOrdIsSign() != null && orderModel.getOrdIsSign().equals(Global.NO + "")) {
				HttpResult sapHttpResult = sapPurchaseService.changeSapOrderStatus(orderModel);
				if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					logger.error(sapHttpResult.getMsg());
					return HttpResult.error("sap返回：" + sapHttpResult.getMsg());
				}
			}
			if (supplyDeal.getDeptId() != null && supplyDeal.getDeptId().equals(ContractTypeEnum.zkh.getValue())) {
				// 调用震坤行接口
				HttpResult zkHttpResult = zkhService.addZkhOrder(supplyDeal.getInqId(), contractModel.getOrdCode());
				if (zkHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(zkHttpResult.getMsg());
				}
			}
		}
		if (result > 0) {
			httpResult.setMsg(contractModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(contractModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(contractModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	public HttpResult back(String ctrId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(ctrId)) {
			return HttpResult.error("参数不能为空");
		}
		ContractModel contractModel = contractDao.load(ctrId);
		contractModel.setStatus(Global.NO + "");
		int result = contractDao.update(contractModel);
		if (result > 0) {
			httpResult.setMsg("撤回成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult delete(String ctrId) {
		if (!StringUtils.isNotNull(ctrId)) {
			return HttpResult.error("参数不能为空");
		}
		ContractModel contractModel = contractDao.load(ctrId);
		if (!contractModel.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}

		HttpResult httpResult = new HttpResult();
		int result = contractDao.delete(ctrId);
		OrderModel orderModel = orderDao.load(contractModel.getOrdId());
		orderModel.setStatus(Global.YES + "");
		result += orderDao.update(orderModel);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<ContractModel> list = contractDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), ContractModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
